﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ZhimeiSoft.CharmManager.Client.Forms.Utils
{
    public static class TypeHelper
    {

        public static void ParseGenericType(string typeAssem, int indexStart, out string typeName, out string assemName)
        {
            int len = typeAssem.Length;
            int depth = 1;

            int index = indexStart;
            while (depth > 0 && (++index < len - 1))
            {
                if (typeAssem[index] == '[')
                    depth++;
                else if (typeAssem[index] == ']')
                    depth--;
            }

            if (depth > 0 || index >= len)
            {
                typeName = null;
                assemName = null;
            }
            else
            {
                index = typeAssem.IndexOf(',', index);

                // comma must be present, and can't be last character 
                if ((index >= 0) && (index < (len - 1)))
                {
                    typeName = typeAssem.Substring(0, index);
                    typeName = typeName.Trim();
                    assemName = typeAssem.Substring(index + 1);
                    assemName = assemName.Trim();
                }
                else
                {
                    typeName = null;
                    assemName = null;
                }
            }
        }

        public static void ParseType(string typeAssem, out string typeName, out string assemName)
        {
            string value = typeAssem;

            int genericTypeIndex = value.IndexOf("[");
            if ((genericTypeIndex >= 0) && (genericTypeIndex < (value.Length - 1)))
            {
                ParseGenericType(value, genericTypeIndex, out typeName, out assemName);
            }
            else
            {
                int index = value.IndexOf(",");

                // comma must be present, and can't be last character 
                if (index == 0 && value.Length > 1)
                {
                    typeName = null;
                    assemName = value.Substring(1);
                }
                else if ((index >= 0) && (index < (value.Length - 1)))
                {
                    typeName = value.Substring(0, index);
                    typeName = typeName.Trim();
                    assemName = value.Substring(index + 1);
                    assemName = assemName.Trim();
                }
                else if (index > 0)
                {
                    typeName = value.Substring(0, index);
                    assemName = null;
                }
                else
                {
                    typeName = null;
                    assemName = null;
                }
            }
        }
    }
}
